package com.zzsy.carosshopprojects.activitys.home.mainpage.orderamount;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yatoooon.screenadaptation.ScreenAdapterTools;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.adapter.OrderAmountAdapter;
import com.zzsy.carosshopprojects.base.BaseFragment;
import com.zzsy.carosshopprojects.bean.MessageEvent;
import com.zzsy.carosshopprojects.bean.OrderBean;
import com.zzsy.carosshopprojects.bean.OrderZongBean;
import com.zzsy.carosshopprojects.util.ConverterHelper;
import com.zzsy.carosshopprojects.util.StringUtils;
import com.zzsy.carosshopprojects.view.refreshview.RefreshView;
import com.zzsy.carosshopprojects.view.refreshview.SpacesItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * 订单金额
 */
public class OrderAmountFragment extends BaseFragment implements RefreshView.RefreshHelper {
    public static OrderAmountFragment newInstance() {
        OrderAmountFragment orderAmountFragment = new OrderAmountFragment();
        return orderAmountFragment;
    }

    @BindView(R.id.ll_click)
    LinearLayout llClick;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.img_down)
    ImageView imgDown;
    @BindView(R.id.ll_views)
    LinearLayout llViews;
    @BindView(R.id.tv_wechat_amount)
    TextView tvWechatAmount;
    @BindView(R.id.tv_wechat_count)
    TextView tvWechatCount;
    @BindView(R.id.tv_alpay_amount)
    TextView tvAlpayAmount;
    @BindView(R.id.tv_alpay_count)
    TextView tvAlpayCount;
    @BindView(R.id.tv_banacl_amount)
    TextView tvBanaclAmount;
    @BindView(R.id.tv_banacl_count)
    TextView tvBanaclCount;
    @BindView(R.id.tv_bank_amount)
    TextView tvBankAmount;
    @BindView(R.id.tv_bank_count)
    TextView tvBankCount;
    @BindView(R.id.smartRefresh)
    RefreshView smartRefresh;
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.no_data_view)
    LinearLayout emptyView;
    private OrderAmountMode orderAmountMode;
    private int page = 1;
    private boolean isShowEmpty = true;
    private boolean isShowDialog = true;
    private int kind = 0;//0 下拉刷新 1 加载更多
    List<OrderBean.OrdersBean> listData;
    private OrderAmountAdapter orderAmountAdapter;
    private int isShow = 1;

    @Override
    protected int initLayout() {
        return R.layout.fg_orderamount;
    }

    @Override
    protected void initView(View view) {
        orderAmountAdapter = new OrderAmountAdapter(getContext(), null, 0);
        listData = new ArrayList<>();
        smartRefresh.setRefreshHelper(this);
        initTitle(view, getResources().getString(R.string.TotalReceipts), getActivity());
        recycleView.setLayoutManager(new LinearLayoutManager(context));
        int space = ScreenAdapterTools.getInstance().loadCustomAttrValue(20);
        recycleView.addItemDecoration(new SpacesItemDecoration(space));
        recycleView.setAdapter(orderAmountAdapter);
        orderAmountAdapter.setOnItemClickListener((v, position) -> {
            start(OrderAmountDetailFragment.newInstance(orderAmountAdapter.getListData().get(position).getOrderNumber()));
        });
    }

    @Override
    protected void initData(Context mContext) {
        orderAmountMode = getViewModelProvider().get(OrderAmountMode.class);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void loadMethod() {
        geShiftStatisticsByTerminalId();
        showData();
    }

    @OnClick({R.id.ll_click})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_click:
                if (isShow % 2 == 0) {
                    llViews.setVisibility(View.GONE);
                    setShowTitle(false);
                } else {

                    setShowTitle(true);
                }

                isShow++;
                break;

        }
    }

    private void geShiftStatisticsByTerminalId() {
        orderAmountMode.getLiveDataOz().observe(this, orderZongBean -> {
            setDataUI(orderZongBean);
        });
        orderAmountMode.geShiftStatisticsByTerminalId(getContext());
    }

    /**
     * 展示列表数据
     */
    private void showData() {
        orderAmountMode.getLiveData().observe(this, orderBeans -> {
            if (orderBeans == null) {
                smartRefresh.finishState();
                return;
            }
            listData.addAll(orderBeans);
            orderAmountAdapter.setListData(listData);
            orderAmountAdapter.notifyDataSetChanged();
            if (!isShowDialog) {
                switch (kind) {
                    case 0:
                        smartRefresh.finishRefresh();
                        break;
                    case 1:
                        smartRefresh.finishLoadMore();
                        if (orderBeans != null && orderBeans.size() > 0) {
                        } else
                            smartRefresh.finishLoadMoreWithNoMoreData();
                        break;
                }
            }
            Log.d("====","11112222");
            setEmptyData();
        });
        orderAmountMode.getOrdersByTerminalId(getContext(), page + "", isShowDialog);
    }

    /**
     * 如果没用数据是否显示空View
     */
    private void setEmptyData() {
        if (isShowEmpty) {
            if (listData == null || listData.size() == 0) {
                emptyView.setVisibility(View.VISIBLE);
            } else {
                emptyView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onRefresh() {
        listData.clear();
        orderAmountAdapter.notifyDataSetChanged();
        kind = 0;
        page = 1;
        isShowEmpty = true;
        isShowDialog = false;
        orderAmountMode.getOrdersByTerminalId(getContext(), page + "", isShowDialog);
    }

    @Override
    public void onLoadMore() {
        isShowEmpty = false;
        isShowDialog = false;
        kind = 1;
        page++;
        orderAmountMode.getOrdersByTerminalId(getContext(), page + "", isShowDialog);
    }

    /**
     * 更新首页UI
     */
    private void setDataUI(OrderZongBean baseBean) {
        String aliPayAmount = baseBean.getAliPayAmount();
        String aliPayCount = baseBean.getAliPayCount();
        String unionPayAmount = baseBean.getUnionPayAmount();
        String unionPayCount = baseBean.getUnionPayCount();
        String weiXinPayAmount = baseBean.getWeiXinPayAmount();
        String weiXinPayCount = baseBean.getWeiXinPayCount();
        String balancePayAmount = baseBean.getBalancePayAmount();
        String balancePayCount = baseBean.getBalancePayCount();
        if (!StringUtils.isEmpty(aliPayAmount)) {
            String aliPayAmountStr = ConverterHelper.toBigDecimal(aliPayAmount).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            tvAlpayAmount.setText("支付宝总收:" + aliPayAmountStr + "元");
        }
        if (!StringUtils.isEmpty(unionPayAmount)) {
            String unionPayAmountStr = ConverterHelper.toBigDecimal(unionPayAmount).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            tvBankAmount.setText("银联总收:" + unionPayAmountStr + "元");
        }
        if (!StringUtils.isEmpty(weiXinPayAmount)) {
            String weiXinPayAmountStr = ConverterHelper.toBigDecimal(weiXinPayAmount).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            tvWechatAmount.setText("微信总收:" + weiXinPayAmountStr + "元");
        }
        if (!StringUtils.isEmpty(balancePayAmount)) {
            String balancePayAmountStr = ConverterHelper.toBigDecimal(balancePayAmount).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
            tvBanaclAmount.setText("余额总收:" + balancePayAmountStr + "元");
        }
        tvWechatCount.setText("微信总订单数:" + weiXinPayCount);
        tvAlpayCount.setText("支付宝总订单数:" + aliPayCount);
        tvBankCount.setText("银联总订单数:" + unionPayCount);
        tvBanaclCount.setText("余额总订单数:" + balancePayCount);
    }

    private void setShowTitle(boolean isShow) {
        if (isShow) {
            tvTitle.setText("收起");
            llViews.setVisibility(View.VISIBLE);
            imgDown.setImageResource(R.mipmap.order_up);
        } else {
            tvTitle.setText("展开");
            llViews.setVisibility(View.GONE);
            imgDown.setImageResource(R.mipmap.order_down);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        switch (event.message) {
            case MessageEvent.TUIKUAN:
                geShiftStatisticsByTerminalId();
                smartRefresh.autoRefresh();
                break;

        }
    }
}
